package com.yaxin.mq.producer;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.yaxin.mq.config.RabbitConfig;
import com.yaxin.mq.entity.OutMqMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;
import com.fasterxml.jackson.core.JsonProcessingException;

/**
 * @author lgj
 * @version 1.0
 * @description rabbitMQ生产者
 * @date 2025/7/18 14:49
 */
@Slf4j
@Component
public class NormalRabbitProducer {

    @Resource
    private RabbitTemplate rabbitTemplate;
    private final ObjectMapper objectMapper = new ObjectMapper();


    public void sendSubmission(String message) {
        rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_NAME, RabbitConfig.ROUTING_KEY_SUBMISSION, message,new CorrelationData(UUID.randomUUID().toString()));
        log.info("【生产者】简历投递 Message send: " + message);
    }

    /**
     * 发送HR系统结构化消息
     */
    public <T> void sendOutMqMessage(String message) {
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setExpiration("60000"); // 60秒，单位为毫秒

        // 创建消息对象
        Message msg = new Message(message.getBytes(), messageProperties);

        // 发送消息
        rabbitTemplate.send(
            RabbitConfig.EXCHANGE_NAME,
            RabbitConfig.ROUTING_KEY_OUTPERSONS,
            msg,
            new CorrelationData(UUID.randomUUID().toString())
        );
        log.info("外协已审批人员 Message send: " + message);
    }

    /**
     * 批量发送HR消息
     * @param messages 消息列表
     * @param <T> 泛型数据类型
     */
    public <T> void sendBatchOutMqMessages(List<OutMqMessage<T>> messages) {
        messages.forEach(msg -> {
            try {
                String jsonMessage = objectMapper.writeValueAsString(msg);
                rabbitTemplate.convertAndSend(
                    RabbitConfig.EXCHANGE_NAME,
                    RabbitConfig.ROUTING_KEY_OUTPERSONS,
                    jsonMessage,
                    new CorrelationData(UUID.randomUUID().toString())
                );
                log.debug("【生产者】批量HR消息 sent: {}", msg);
            } catch (JsonProcessingException e) {
                log.error("批量HR消息序列化失败", e);
            }
        });
        log.info("【生产者】批量HR消息发送完成，共{}条", messages.size());
    }
}
